﻿using AutoMapper;
using MediatR;
using SqlSugar;
using WarehouseManagement.Application.Command.RequestTransferCommand;
using WarehouseManagement.Domain.Entity;
using WarehouseManagement.Infrstructre.Interface;

namespace WarehouseManagement.Application.CommandHandler.RequestTransferCommandHandlers
{
    /// <summary>
    /// 修改调拨申请
    /// </summary>
    public class RequestTransferUpdCommandHandlers : IRequestHandler<RequestTransferUpdCommand, int>
    {
        private readonly IRequestTransferRepository _requestTransferRep;
        private readonly IAllocationProductAppRepository _allocationProductAppRep;
        protected readonly IMapper _mapper;
        protected readonly ISqlSugarClient db;

        public RequestTransferUpdCommandHandlers(IRequestTransferRepository requestTransferRep, IAllocationProductAppRepository allocationProductAppRep, IMapper mapper, ISqlSugarClient db)
        {
            this._requestTransferRep = requestTransferRep;
            this._allocationProductAppRep = allocationProductAppRep;
            this._mapper = mapper;
            this.db = db;
        }

        public async Task<int> Handle(RequestTransferUpdCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                //修改采购退货
                var se = await db.Queryable<RequestTransfers>()
                                 .Where(c => c.RequestTransfersId == request.updDto.RequestTransfersId)
                .FirstAsync();

                var preProduction = _mapper.Map<RequestTransfers>(request.updDto);
                int Item = await _requestTransferRep.UpdateAsync(preProduction);


                //删除调拨申请产品表中原有的数据
                var itemsToDelete = await db.Queryable<AllocationProductApp>()
                                  .Where(c => c.RTNumber == se.RTNumber)
                                  .ToListAsync();
                foreach (var item in itemsToDelete)
                {
                    await _allocationProductAppRep.DelRange(new List<AllocationProductApp> { item });
                }


                foreach (var subpiece in request.updDto.upddto)
                {
                    AllocationProductApp items = new AllocationProductApp();
                    items.AllocationProductAppId = subpiece.AllocationProductAppId;
                    items.RTNumber = preProduction.RTNumber;
                    items.ProductId = subpiece.ProductId;
                    items.PNumber = subpiece.PNumber;
                    items.PName = subpiece.PName;
                    items.PSpec = subpiece.PSpec;
                    items.PUnit = subpiece.PUnit;
                    items.APANumberApplication = subpiece.APANumberApplication;
                    items.APASmark = subpiece.APASmark;
                    items.AddName = preProduction.AddName;
                    items.AddTime = preProduction.AddTime;
                    items.UpdName = preProduction.UpdName;
                    items.UpdTime = preProduction.UpdTime;
                    items.Office_Id = preProduction.Office_Id;
                    items.User_Id = preProduction.User_Id;
                    await _allocationProductAppRep.AddAsync(items);
                }
                // 提交事务
                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception ex)
            {
                // 捕获异常并回滚事务
                db.Ado.RollbackTran();
                // 可以记录日志以便调试
                throw new Exception("事务失败，已回滚所有操作", ex);
            }
        }
    }
}
